package socket;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class Server {
    private ServerSocket serverSocket;
    private ExecutorService threadpool;
    public Server(){
        try {
            System.out.println("正在启动服务端");
            serverSocket = new ServerSocket(8088);
            threadpool = Executors.newFixedThreadPool(5);
            System.out.println("服务端启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start() {
        try {
            System.out.println("等待客户端连接");
            while (true) {
                Socket socket = serverSocket.accept();

                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();
                System.out.println(t.getName()+"连接了");
                threadpool.execute(handler);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
    private class ClientHandler implements Runnable{
        private Socket socket;
        public ClientHandler(Socket socket){
            this.socket = socket;
        }
        public void run(){
            try{
                InputStream in = socket.getInputStream();
                int len;
                //int d = in.read();
                while((len = in.read())!=-1) {
                    byte[] data = new byte[len];
                    in.read(data);
                    String line = new String(data, StandardCharsets.UTF_8);
                    System.out.println(line);
                    //System.out.println(d);
                }
            System.out.println("客户端断开连接");
        } catch (IOException e) {
            e.printStackTrace();
        }
        }
    }
}
